import React from "react";
import { Form, Input, Button, Checkbox, notification } from "antd";
import { useHistory } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { Ajax } from "../../Utils/AjaxConfig";
import styles from "./RegisterPage.module.css";
export const RegisterForm: React.FC = () => {
  const history = useHistory();
  const { t } = useTranslation();
  const layout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
  };
  const tailLayout = {
    wrapperCol: { offset: 8, span: 16 },
  };

  const onFinish = async (values: any) => {
    try {
      await Ajax.post("/auth/register", {
        email: values.useruEmail,
        password: values.password,
        confirmPassword: values.confrm,
      });
      notification["success"]({
        message: "注册成功",
        description: "注册成功，即将跳转到登录界面",
        duration: 2,
      });
      history.push("/singIn");
    } catch (error) {
      notification["error"]({
        message: "注册失败，请稍后重试",
        description: error.title,
        duration: 1,
      });
    }
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log("Failed:", errorInfo);
  };

  const emailRef = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

  return (
    <>
      <Form
        {...layout}
        name="basic"
        initialValues={{ remember: true }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        className={styles["register-form"]}
      >
        <Form.Item
          label={t("form.email")}
          name="useruEmail"
          hasFeedback
          rules={[
            {
              required: true,
              message: t("form.email_message"),
            },
            { pattern: emailRef, message: t("form.email_message_error") },
          ]}
        >
          <Input placeholder="请输入邮箱地址" />
        </Form.Item>
        <Form.Item
          label={t("form.password")}
          name="password"
          hasFeedback
          rules={[{ required: true, message: t("form.password_message") }]}
        >
          <Input.Password placeholder="请输入密码" />
        </Form.Item>

        <Form.Item
          label={t("form.confirm_password")}
          name="confrm"
          hasFeedback
          rules={[
            { required: true, message: t("form.confirm_password_message") },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue("password") === value) {
                  return Promise.resolve();
                }
                return Promise.reject(t("form.confirm_message_error"));
              },
            }),
          ]}
        >
          <Input.Password placeholder="请再次输入密码" />
        </Form.Item>

        <Form.Item {...tailLayout} name="remember" valuePropName="checked">
          <Checkbox>{t("form.remember_me")}</Checkbox>
        </Form.Item>
        <Form.Item {...tailLayout}>
          <Button type="primary" htmlType="submit">
            {t("form.registration")}
          </Button>
        </Form.Item>
      </Form>
    </>
  );
};
